package com.xhsj.user.security.service;

import com.xhsj.user.security.IntegrationAuthentication;
import com.xhsj.user.security.IntegrationAuthenticator;
import com.xhsj.user.security.entity.LoginUser;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.common.exceptions.OAuth2Exception;
import org.springframework.stereotype.Service;


/**
 * 根据用户名获取用户<br>
 * <p>
 * 密码校验请看下面两个类
 *
 * @author suxiaolin
 * @date 2020/8/27 09:38
 * @see org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider
 * @see org.springframework.security.authentication.dao.DaoAuthenticationProvider
 */
@Slf4j
@Service
public class MyUserDetailsService implements IntegrationAuthenticator {
    private static final String AUTH_TYPE = "pwd";
    @Autowired
    private BCryptPasswordEncoder passwordEncoder;
    @Autowired
    TbGlobalUserService tbGlobalUserService;

    @Override
    public LoginUser authenticate(IntegrationAuthentication entity) {
        long l = System.currentTimeMillis();
        String username = entity.getAuthParameter("username");
        log.info("传入的参数是: {}", username);
        //密码登录
        LoginUser user = tbGlobalUserService.findByPhoneNumber(username);
        if (user != null) {
            String password = entity.getAuthParameter("password");
            if (!passwordEncoder.matches(password,user.getPassword())) {
                log.error(this.getClass().getName()+":用户名或密码错误");
                throw new OAuth2Exception("用户名或密码错误");
            }
            if (user.getStatus() == 1) {
                log.error(this.getClass().getName()+":用户已作废");
                throw new OAuth2Exception("用户已作废");
            }
        }else{
            log.error(this.getClass().getName()+":用户不存在");
            throw new OAuth2Exception("用户不存在");
        }
        long l1 = System.currentTimeMillis();
        System.err.println("耗时："+(l1-l));
        return user;
    }

    @Override
    public void prepare(IntegrationAuthentication entity) {

    }

    @Override
    public boolean support(IntegrationAuthentication entity) {

        boolean equals = AUTH_TYPE.equals(entity.getAuthType());
        if (equals) {
            System.err.println("MyUserDetailsService support");
        }
        return equals;
    }

    @Override
    public void complete(IntegrationAuthentication entity) {

    }
}